package com.smartmedi.ai.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smartmedi.ai.common.BaseResponse;
import com.smartmedi.ai.common.ResultUtils;
import com.smartmedi.ai.domain.entity.JhInMrFile;
import com.smartmedi.ai.service.JhInMrFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 电子病历文件管理控制器
 */
@RestController
@RequestMapping("/ai/file")
@RequiredArgsConstructor
@Slf4j
public class JhInMrFileController {

    private final JhInMrFileService jhInMrFileService;

    /**
     * 查询文件列表
     *
     * @param pageNum   当前页码
     * @param pageSize  每页记录数
     * @param fileName  文件名关键字
     * @param fileType  文件类型
     * @param recordId  关联病历ID
     * @param sortField 排序字段
     * @param sortOrder 排序顺序
     * @return 文件列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getFileList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String fileName,
            @RequestParam(required = false) String fileType,
            @RequestParam(required = false) String recordId,
            @RequestParam(required = false) String sortField,
            @RequestParam(required = false) String sortOrder) {

        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建分页对象
            Page<JhInMrFile> page = new Page<>(pageNum, pageSize);
            
            // 查询文件列表
            Page<JhInMrFile> filePage = jhInMrFileService.getFileList(page, fileName, fileType, recordId, sortField, sortOrder);
            
            // 为了安全，清空返回结果中的文件内容
            filePage.getRecords().forEach(file -> file.setFileContent(null));
            
            result.put("code", 0);
            result.put("msg", "获取文件列表成功");
            result.put("data", filePage);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取文件列表失败", e);
            result.put("code", 500);
            result.put("msg", "获取文件列表失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取文件详情
     *
     * @param id 文件ID
     * @return 文件详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getFileDetail(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            JhInMrFile file = jhInMrFileService.getById(id);
            
            if (file == null) {
                result.put("code", 404);
                result.put("msg", "文件不存在");
                return ResponseEntity.ok(result);
            }
            
            // 为了安全，清空返回结果中的文件内容
            file.setFileContent(null);
            
            result.put("code", 0);
            result.put("msg", "获取文件详情成功");
            result.put("data", file);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取文件详情失败", e);
            result.put("code", 500);
            result.put("msg", "获取文件详情失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 下载文件
     *
     * @param id 文件ID
     * @return 文件内容
     */
    @GetMapping("/download/{id}")
    public ResponseEntity<?> downloadFile(@PathVariable Long id) {
        try {
            JhInMrFile file = jhInMrFileService.getById(id);
            
            if (file == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 404);
                result.put("msg", "文件不存在");
                return ResponseEntity.ok(result);
            }
            
            // 获取文件内容
            byte[] fileContent = jhInMrFileService.getFileContent(id);
            
            // 设置响应头
            String encodedFileName = URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(file.getFileType()));
            headers.setContentDispositionFormData("attachment", encodedFileName);
            headers.setContentLength(fileContent.length);
            
            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("下载文件失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "下载文件失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取文件预览URL
     *
     * @param id 文件ID
     * @return 预览URL
     */
    @GetMapping("/preview/{id}")
    public ResponseEntity<Map<String, Object>> getPreviewUrl(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            JhInMrFile file = jhInMrFileService.getById(id);
            
            if (file == null) {
                result.put("code", 404);
                result.put("msg", "文件不存在");
                return ResponseEntity.ok(result);
            }
            
            // 获取文件预览URL
            String previewUrl = jhInMrFileService.generatePreviewUrl(id);
            
            result.put("code", 0);
            result.put("msg", "获取预览URL成功");
            result.put("data", previewUrl);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取文件预览URL失败", e);
            result.put("code", 500);
            result.put("msg", "获取文件预览URL失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 上传文件
     *
     * @param file     文件
     * @param recordId 关联病历ID
     * @param fileDesc 文件描述
     * @return 上传结果
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("recordId") String recordId,
            @RequestParam(value = "fileDesc", required = false) String fileDesc) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (file.isEmpty()) {
                result.put("code", 400);
                result.put("msg", "上传文件不能为空");
                return ResponseEntity.ok(result);
            }
            
            // 上传文件
            Long fileId = jhInMrFileService.uploadFile(file, recordId, fileDesc);
            
            result.put("code", 0);
            result.put("msg", "上传文件成功");
            result.put("data", fileId);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("上传文件失败", e);
            result.put("code", 500);
            result.put("msg", "上传文件失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 从FTP导入文件
     *
     * @param ftpFilePath FTP文件路径
     * @param recordId    关联病历ID
     * @param fileDesc    文件描述
     * @return 导入结果
     */
    @PostMapping("/import-ftp")
    public ResponseEntity<Map<String, Object>> importFromFtp(
            @RequestParam("ftpFilePath") String ftpFilePath,
            @RequestParam("recordId") String recordId,
            @RequestParam(value = "fileDesc", required = false) String fileDesc) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            Long fileId = jhInMrFileService.importFromFtp(ftpFilePath, recordId, fileDesc);
            
            result.put("code", 0);
            result.put("msg", "从FTP导入文件成功");
            result.put("data", fileId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("从FTP导入文件失败", e);
            result.put("code", 500);
            result.put("msg", "从FTP导入文件失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 删除文件
     *
     * @param id 文件ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteFile(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = jhInMrFileService.removeById(id);
            
            if (!success) {
                result.put("code", 404);
                result.put("msg", "文件不存在或删除失败");
                return ResponseEntity.ok(result);
            }
            
            result.put("code", 0);
            result.put("msg", "删除文件成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("删除文件失败", e);
            result.put("code", 500);
            result.put("msg", "删除文件失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 批量删除文件
     *
     * @param ids 文件ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchDeleteFiles(@RequestBody Long[] ids) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (ids == null || ids.length == 0) {
                result.put("code", 400);
                result.put("msg", "未选择要删除的文件");
                return ResponseEntity.ok(result);
            }
            
            boolean success = jhInMrFileService.removeByIds(java.util.Arrays.asList(ids));
            
            result.put("code", 0);
            result.put("msg", "批量删除文件成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("批量删除文件失败", e);
            result.put("code", 500);
            result.put("msg", "批量删除文件失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }
}
